package com.shopping.common.core.util;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.shopping.common.core.object.UserExportData;
import com.shopping.common.sp.model.user.User;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author: zlw
 * @date: 2024/9/13
 */
public class ExcelExportUtil {

    /**
     * 导出用户数据
     * @param userList
     */
    public static File export(List<User> userList) throws IOException {
        long copyStartTime = System.currentTimeMillis();
        //手动转换 节约时间
        // 手动转换对象，替换 BeanUtil.copyToList 避免不必要的开销
        List<UserExportData> userExportDataList = copyUserToUserExportData(userList);
        System.out.println("转换的数据量大小:{}" + userExportDataList.size());
        long copyEndTime = System.currentTimeMillis();
        long copyRunTime = copyEndTime - copyStartTime;
        System.out.println("转换十万条数据所花费时间: {} " + copyRunTime / 1000 + "秒");
        String filePath = "D://myProject/export/";
        //写入文件
        File file = new File(filePath + UUID.randomUUID() + ".xlsx");


        //使用 EasyExcel 导出数据
        EasyExcel.write(file, UserExportData.class)
                .sheet("用户信息")
                .doWrite(userExportDataList);
        System.out.println("导出成功");
        return file;
    }

    private static List<UserExportData> copyUserToUserExportData(List<User> userList) {
        List<UserExportData> userExportDataList = userList.stream().map(user -> {
            UserExportData userExportData = new UserExportData();
            userExportData.setUserId(user.getUserId());
            userExportData.setUserName(user.getUserName());
            userExportData.setMobilePhone(user.getMobilePhone());
            userExportData.setPassWord(user.getPassWord());
            userExportData.setCreateUserId(user.getCreateUserId());
            userExportData.setCreateUserName(user.getCreateUserName());
            userExportData.setCreateTime(user.getCreateTime());
            userExportData.setUpdateUserId(user.getUserId());
            userExportData.setUpdateUserName(user.getUpdateUserName());
            userExportData.setUpdateTime(user.getUpdateTime());
            userExportData.setDeletedFlag(user.getDeletedFlag());
            return userExportData;
        }).collect(Collectors.toList());
        return userExportDataList;
    }
}